﻿using System;
using System.Collections.Generic;
using Castle.Windsor;
using CommonServiceLocator.WindsorAdapter;
using Microsoft.Practices.ServiceLocation;

namespace DosTexPrj.Implement.NHibernate
{
    public static class MyServiceLocator
    {
        private static IWindsorContainer _container;

        static MyServiceLocator()
        {
        }

        public static void SetContainer(IWindsorContainer container)
        {
            _container = container;

            MakeSureContainerNotNull();

            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(_container));
        }

        public static object DoGetInstance(Type serviceType, string key)
        {
            MakeSureContainerNotNull();

            return ServiceLocator.Current.GetInstance(serviceType, key);
        }

        public static object DoGetInstance(Type serviceType)
        {
            MakeSureContainerNotNull();

            return ServiceLocator.Current.GetInstance(serviceType);
        }

        public static TType DoGetInstance<TType>()
        {
            MakeSureContainerNotNull();

            return ServiceLocator.Current.GetInstance<TType>();
        }

        public static TType DoGetInstance<TType>(string key)
        {
            MakeSureContainerNotNull();

            return ServiceLocator.Current.GetInstance<TType>(key);
        }

        public static IEnumerable<object> DoGetAllInstances(Type serviceType)
        {
            MakeSureContainerNotNull();

            return ServiceLocator.Current.GetAllInstances(serviceType);
        }

        public static IEnumerable<TType> DoGetAllInstances<TType>()
        {
            MakeSureContainerNotNull();

            return ServiceLocator.Current.GetAllInstances<TType>();
        }

        private static void MakeSureContainerNotNull()
        {
            if (_container == null)
                throw new NullReferenceException();
        }
    }
}